
from gi.repository import Gtk, Gdk
from led import Led
from solver import Solver
import random

""" A module """

class Grid(Gtk.Grid):
    """ A grid is a very cool guy """
    def __init__(self, size = 5):
        Gtk.Grid.__init__(self)
        self.solve = False
        self.set_vexpand(True)
        self.set_row_homogeneous(True)
        self.set_column_homogeneous(True)
        leds = [[Led() for _ in range(size)] for _ in range(size)]
        self.leds = leds
        self.solver = Solver(leds)
        """ The solver object. """
        for i in range(size):
            for j in range(size):
                led = leds[i][j]
                # FIXME ALL_EVENTS
                led.add_events(Gdk.EventMask.ALL_EVENTS_MASK)
                led.connect('button-press-event', self.clicked_callback)
                self.attach(led, i, j, 1, 1)
                if i > 0: led.neighbors.append(leds[i - 1][j])
                if i < size - 1: led.neighbors.append(leds[i + 1][j])
                if j > 0: led.neighbors.append(leds[i][j - 1])
                if j < size - 1: led.neighbors.append(leds[i][j + 1])

    def clicked_callback(self, widget, event):
        # If the callback it's for a double or a triple click, just don't
        # handle it.
        _, click_count = event.get_click_count()
        if click_count > 1:
            return
        # handle the callback by the point of view of the widget.
        widget.clicked_callback()
        if self.solve:
            if widget.mark:
                widget.mark = False
            else:
                self.solver.mark_solution()
                self.queue_draw()

    def set_solve(self, solve):
        self.solve = solve
        for row in self.leds:
            for led in row:
                led.mark = False
                led.queue_draw()
        if self.solve:
            self.solver.mark_solution()

    def scramble(self):
        for i in range(len(self.leds) ** 2):
            row = random.choice(self.leds)
            led = random.choice(row)
            led.clicked_callback()
        if self.solve:
            self.solver.mark_solution()
